# -*- Coding: UTF-8 -*-
# functions.py
# @author: SongLiangCao
# @email: 2023733547@qq.com
# @description: none
# @created: 2021-12-16T16:32:11.547Z+08:00
# @last-modified: 2022-01-10T21:22:50.277Z+08:00
#

import numpy as np


def softmax(x):
    """
    Parameters
    ----------
    x: input data

    Returns
    --------

    """
    if x.ndim == 2:
        x = x.T
        x = x - np.max(x, axis=0)
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T

    x = x - np.max(x)  # Prevent overflow
    return np.exp(x) / np.sum(np.exp(x))


def im2col(input_data, filter_h, filter_w, stride=1, pad=0):
    """
    Parameters
    ----------
    input_data : input data consisting of a 4-dimensional array of 
                (data volume, channel, height, length)
    filter_h : filter height
    filter_w : filter length
    stride : filter stride
    pad : filling

    Returns
    -------
    col : Two-dimensional array
    """
    N, C, H, W = input_data.shape
    out_h = (H + 2*pad - filter_h)//stride + 1
    out_w = (W + 2*pad - filter_w)//stride + 1

    img = np.pad(input_data, [(0, 0), (0, 0), (pad, pad), (pad, pad)], 'constant')
    col = np.zeros((N, C, filter_h, filter_w, out_h, out_w))

    for y in range(filter_h):
        y_max = y + stride*out_h
        for x in range(filter_w):
            x_max = x + stride*out_w
            col[:, :, y, x, :, :] = img[:, :, y:y_max:stride, x:x_max:stride]

    col = col.transpose(0, 4, 5, 1, 2, 3).reshape(N*out_h*out_w, -1)
    return col


def col2im(col, input_shape, filter_h, filter_w, stride=1, pad=0):
    """
    Parameters
    ----------
    col :
    input_shape : shape of input data
    filter_h: filter height
    filter_w: filter width
    stride: filter stride
    pad: filling

    Returns
    -------
    images type array
    """
    N, C, H, W = input_shape
    out_h = (H + 2*pad - filter_h)//stride + 1
    out_w = (W + 2*pad - filter_w)//stride + 1
    col = col.reshape(N, out_h, out_w, C, filter_h, filter_w).transpose(0, 3, 4, 5, 1, 2)

    img = np.zeros((N, C, H + 2*pad + stride - 1, W + 2*pad + stride - 1))
    for y in range(filter_h):
        y_max = y + stride*out_h
        for x in range(filter_w):
            x_max = x + stride*out_w
            img[:, :, y:y_max:stride, x:x_max:stride] += col[:, :, y, x, :, :]

    return img[:, :, pad:H + pad, pad:W + pad]


def cross_entropy_error(y, t):
    """cross entropy error

    Parameters
    ----------
    y: Input data
    t: monitoring data

    Returns
    ---------

    """
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)

    # When the supervision data is a one-hot-vector, it is converted to the index of the correct solution label
    if t.size == y.size:
        t = t.argmax(axis=1)

    batch_size = y.shape[0]
    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
